//
//  ViewController.swift
//  GCDDemo
//
//  Created by dayu on 15/6/9.
//  Copyright (c) 2015年 dayu. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

//        let str: String = "hello";
        let strOC: NSString = "hello";
        let str: String = "hello";
        
        let obj: NSDate.Type;
        
       let function = delay(2) {
            println("+++++++");
        };
        delay(1.823) {
            [weak self] in
            if let strongSelf = self {
                strongSelf.cancel(function);
            }
        }
        
    }

    typealias Task = (cancel: Bool) -> ();
    
    func delay(time: NSTimeInterval, task: ()->()) -> Task? {
        
        func dispatch_later(block:()->()) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(time * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), block)
        }
        var closure: dispatch_block_t? = task;
        var result: Task?;
        
        let delayedClosure: Task = {
            cancel in
            if let internalClosure = closure {
                if cancel == false {
                    dispatch_async(dispatch_get_main_queue(), internalClosure);
                }
                closure = nil;
                result = nil;
            }
            
        }
        result = delayedClosure;
        
        dispatch_later {
            if let delayedClosure = result {
                delayedClosure(cancel: false);
            }
        }
        
        return result;
        
    }
    
    func cancel(task: Task?) {
        task?(cancel: true);
    }
    
    

}

